package com.eco.fanliapp.job.hdkitemjob;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.service.HDKUtils;
import com.eco.fanliapp.service.IAppGoodsService;
import com.eco.fanliapp.service.IUserCashschemeService;
import com.eco.fanliapp.utils.ApiUtils;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.respone.DTKResponse;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取好单库更新商品
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class HDKUpdateGoodsTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(HDKUpdateGoodsTask.class);

    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;


    public HDKUpdateGoodsTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执行好单库商品更新定时任务-DTKItemTask：executeCount=" + executeCount + "--beginTime=" + beginTime);
        long startTime = System.currentTimeMillis();
        long min = 1;
        long back = 500;

        AppCompany com = userCashschemeService.findCompanyAll();
        List<AppGoods> updateAppGoodsList = new ArrayList<>();
        while (true) {

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("sort", "3");
            data.put("back", back);
            data.put("min_id", min);

            try {

                String str = ApiUtils.getData(ApiEnum.UPDATE_ITEM, data);
//                log.info("获取好单库商品列表数据{}", str);
                JSONObject object = JSONObject.parseObject(str);
                AppGoods response = JsonUtils.getJsonToBean(object.toJSONString(), AppGoods.class);
                if (response != null && response.getCode() == 1) { //code等于1代表请求成功
                    JSONArray array = JSONArray.parseArray(object.getJSONArray("data").toJSONString());
                    List<HaoDanKuItemInfo.DataBean> bean = JsonUtils.getJsonToList(array.toJSONString(), HaoDanKuItemInfo.DataBean.class);
                    if (bean == null || bean.size() <= 0) {
                        break;
                    }

                    for (HaoDanKuItemInfo.DataBean haoDanKuItemInfo : bean) {
                        AppGoods appGoods = appGoodsService.findAppGoodsByItemId(haoDanKuItemInfo.getItemid());
                        if (appGoods != null) {
                            AppGoods dataBean = HDKUtils.getAppGoodsFromHDK(haoDanKuItemInfo);
                            dataBean = appGoodsService.getMoneyInfoByGoodsId(com, dataBean);
                            appGoods.setItemType(1);
                            appGoods.setUpdateTime(DateUtils.getNowTimestamp());
//                            dataBean.setTableId(appGoods.getTableId());
                            Integer num = appGoodsMapper.selectAppGoodsByAddUserId(dataBean.getItemid());
                            if (num > 0) {
                                continue;
                            }
                            //判断是否最终金额小于0
                            BigDecimal itemendprice = new BigDecimal(dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice());
                            BigDecimal tkMoney = new BigDecimal(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney());
                            if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                                continue;
                            }
                            String goodsTkMoney = dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney();
                            Double goodsItemendprice = dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice();
                            String goodsItemprice = dataBean.getItemprice() == null ? "0" : dataBean.getItemprice();
                            String goodsCouponendtime = dataBean.getCouponendtime() == null ? "0" : dataBean.getCouponendtime();
                            String goodsCouponstarttime = dataBean.getCouponstarttime() == null ? "0" : dataBean.getCouponstarttime();
                            if (dataBean.getCouponmoney() != (appGoods.getCouponmoney()) || !goodsItemprice.equals(appGoods.getItemprice())
                                    || !goodsItemendprice.equals(appGoods.getItemendprice()) || !goodsTkMoney.equals(appGoods.getTkmoney())
                                    || !goodsCouponendtime.equals(appGoods.getCouponendtime()) || !goodsCouponstarttime.equals(appGoods.getCouponstarttime())) {

                                appGoods.setCouponmoney(dataBean.getCouponmoney());
                                appGoods.setItemendprice(goodsItemendprice);
                                appGoods.setItemprice(goodsItemprice);
                                appGoods.setCouponstarttime(goodsCouponstarttime);
                                appGoods.setCouponendtime(goodsCouponendtime);
                                appGoods.setTkmoney(goodsTkMoney);
                                updateAppGoodsList.add(appGoods);
                            }
                        }
                    }

                } else {
                    log.info("更新好单库商品   请求失败{}", response.getMsg());
                }

                if (updateAppGoodsList.size() > 0 && updateAppGoodsList.size() > 200) {
                    try {
                        boolean i = appGoodsService.updateBatchById(updateAppGoodsList);
                        if (i) {
                            log.info("更新好单库商品   入库商品更新成功 数据size={} ", updateAppGoodsList.size());
                            updateAppGoodsList.clear();
                        } else {
                            log.info("更新好单库商品   入库商品更新失败 数据={} ", updateAppGoodsList.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                min = response.getMinId();
            } catch (Exception e) {
                log.error("更新好单库商品失败");
                break;
            } finally {
                log.info("更新好单库商品   min_id的值{}", min);
            }
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行获取好单库更新商品定时任务任务-DTKItemTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }
}
